
package com.wlcj.www.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

/**
 * 类名：EncryptionUtil  <br />
 *
 * 功能：密文工具
 *
 * @author caoyx <br />
 * 创建时间：2015-01-19 上午09:22:51  <br />
 * @version 2015-01-19
 */
public class EncryptionUtil {
	
	/**
	 * 
	 * 功能：执行MD5摘要运算，UTF-8编码处理字符串 <br/>
	 *
	 * @author caoyx <br/>
	 * @version 2013-12-24 下午05:22:26 <br/>
	 */
	public static byte[] md5(String str) {
		try {
			return md5(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 功能：执行MD5摘要运算，按给定编码处理字符串 <br/>
	 *
	 * @author caoyx <br/>
	 * @version 2015-01-19 上午09:23:30 <br/>
	 */
	
	public static byte[] md5(String str, String encoding) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			//messageDigest.reset();
			digest.update(str.getBytes(encoding));
			
			return digest.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * 功能： 将字节数组，转换为16进制字符串输出，每个字节占两个字符<br/>
	 *
	 * @author caoyx <br/>
	 * @version 2014-2-12 下午04:02:20 <br/>
	 */
	public static String toHexString(byte[] datas) {
		return toHexString(datas, 0, datas.length);
	}
	
	/**
	 * 
	 * 功能：将字节数组，转换为16进制字符串输出，每个字节占两个字符 <br/>
	 *
	 * @author caoyx <br/>
	 * @version 2014-1-3 下午04:17:45 <br/>
	 */
	public static String toHexString(byte[] datas, int begin, int len) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = begin, end = begin + len; i < end; i++) {
			// 转换为16进制字符串
			String hex = Integer.toHexString(0xFF & datas[i]);
			
			if (hex.length() == 1) {
				// 不足两位，前补0
				sb.append("0");
			}
			
			sb.append(hex);
		}
		
		// 转换为大写输出
		return sb.toString();
	}
	
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder("{");
		
		sb.append("name").append(":").append("张三").append("}");
		BASE64Encoder en = new BASE64Encoder();
		System.out.println(en.encode(sb.toString().getBytes()));
	}
}
